package com.gitee.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gitee.dao.WareSkuDao;
import com.gitee.dao.WareSkuLogDao;
import com.gitee.entity.WareSkuEntity;
import com.gitee.entity.WareSkuLogEntity;
import com.gitee.service.WareSkuService;
import io.seata.core.context.RootContext;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    private WareSkuLogDao wareSkuLogDao;

    @Override
    @Transactional
    public void reduct(Long skuId, Integer num) {
        // 0.获取事务id
        String xid = RootContext.getXID();
        //扣减库存
        int lockSkuStock = baseMapper.lockSkuStock(skuId, num, 1L);
        if (lockSkuStock <= 0) {
            throw new RuntimeException("库存不足");
        }

        //记录事务
        WareSkuLogEntity skuLogEntity = new WareSkuLogEntity();
        skuLogEntity.setXid(xid);
        skuLogEntity.setSkuId(skuId);
        skuLogEntity.setWareId(1L);
        skuLogEntity.setStockLocked(num);
        skuLogEntity.setState(0);
        wareSkuLogDao.insert(skuLogEntity);
    }

    @Override
    public boolean confirm(BusinessActionContext ctx) {
        // 1.获取事务id
        String xid = ctx.getXid();
        // 2.根据id删除冻结记录
        int count = wareSkuLogDao.deleteByXId(xid);
        return count == 1;
    }

    @Override
    public boolean cancel(BusinessActionContext ctx) {
        // 1.获取事务id
        String xid = ctx.getXid();
        // 2.根据id查询冻结记录
        WareSkuLogEntity skuLogEntity = wareSkuLogDao.selectByXId(xid);

        // 3.记录恢复锁定的库存
        int unlockStock = baseMapper.unlockStock(skuLogEntity.getSkuId(), skuLogEntity.getWareId(), skuLogEntity.getStockLocked());
        // 4.更新状态
        if (unlockStock > 0) {
            skuLogEntity.setState(2);
            int update = wareSkuLogDao.updateByXId(skuLogEntity);

            return update > 0;
        }

        return false;
    }
}
